import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
import seaborn as sns

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

def analyze_eeg_patterns(file_path):
    """分析脑波数据的变化规律"""
    
    # 读取数据
    print("正在读取脑波数据...")
    df = pd.read_csv(file_path)
    
    # 转换时间戳
    df['timestamp'] = pd.to_datetime(df['timestamp'])
    df = df.sort_values('timestamp')
    
    print(f"数据总行数: {len(df)}")
    print(f"时间跨度: {df['timestamp'].min()} 到 {df['timestamp'].max()}")
    print(f"总时长: {(df['timestamp'].max() - df['timestamp'].min()).total_seconds():.1f} 秒")
    
    # 基本统计信息
    print("\n=== 基本统计信息 ===")
    key_columns = ['attention', 'meditation', 'delta', 'theta', 'lowAlpha', 'highAlpha', 
                   'lowBeta', 'highBeta', 'lowGamma', 'midGamma', 'poorSignal']
    
    for col in key_columns:
        if col in df.columns:
            print(f"{col}: 均值={df[col].mean():.1f}, 标准差={df[col].std():.1f}, 范围=[{df[col].min()}-{df[col].max()}]")
    
    # 分析注意力和冥想状态的变化
    print("\n=== 注意力和冥想状态分析 ===")
    
    # 定义状态等级
    def categorize_level(value):
        if value < 20:
            return '很低'
        elif value < 40:
            return '低'
        elif value < 60:
            return '中等'
        elif value < 80:
            return '高'
        else:
            return '很高'
    
    df['attention_level'] = df['attention'].apply(categorize_level)
    df['meditation_level'] = df['meditation'].apply(categorize_level)
    
    print("注意力状态分布:")
    print(df['attention_level'].value_counts())
    print("\n冥想状态分布:")
    print(df['meditation_level'].value_counts())
    
    # 分析脑电波频段的变化
    print("\n=== 脑电波频段分析 ===")
    wave_columns = ['delta', 'theta', 'lowAlpha', 'highAlpha', 'lowBeta', 'highBeta', 'lowGamma', 'midGamma']
    
    # 计算各频段的相对强度
    df['total_power'] = df[wave_columns].sum(axis=1)
    for col in wave_columns:
        df[f'{col}_ratio'] = df[col] / (df['total_power'] + 1)  # 避免除零
    
    # 分析主导频段
    def get_dominant_wave(row):
        wave_ratios = {col: row[f'{col}_ratio'] for col in wave_columns}
        return max(wave_ratios, key=wave_ratios.get)
    
    df['dominant_wave'] = df.apply(get_dominant_wave, axis=1)
    print("主导脑电波频段分布:")
    print(df['dominant_wave'].value_counts())
    
    # 分析时间序列变化趋势
    print("\n=== 时间序列变化趋势 ===")
    
    # 按时间窗口计算平均值（每30秒）
    df['time_window'] = df['timestamp'].dt.floor('30S')
    time_stats = df.groupby('time_window').agg({
        'attention': 'mean',
        'meditation': 'mean',
        'delta': 'mean',
        'theta': 'mean',
        'lowAlpha': 'mean',
        'highAlpha': 'mean',
        'lowBeta': 'mean',
        'highBeta': 'mean',
        'poorSignal': 'mean'
    }).reset_index()
    
    print(f"时间窗口数量: {len(time_stats)}")
    
    # 检测状态变化点
    print("\n=== 状态变化点检测 ===")
    
    # 计算注意力和冥想的变化率
    df['attention_change'] = df['attention'].diff().abs()
    df['meditation_change'] = df['meditation'].diff().abs()
    
    # 找出显著变化点（变化超过20点）
    significant_attention_changes = df[df['attention_change'] > 20]
    significant_meditation_changes = df[df['meditation_change'] > 20]
    
    print(f"注意力显著变化次数: {len(significant_attention_changes)}")
    print(f"冥想状态显著变化次数: {len(significant_meditation_changes)}")
    
    if len(significant_attention_changes) > 0:
        print("\n注意力显著变化时间点（前5个）:")
        for _, row in significant_attention_changes.head().iterrows():
            print(f"  {row['timestamp']}: {row['attention']:.0f} (变化: {row['attention_change']:.0f})")
    
    # 分析信号质量
    print("\n=== 信号质量分析 ===")
    good_signal = df[df['poorSignal'] <= 25]
    poor_signal = df[df['poorSignal'] > 25]
    
    print(f"良好信号比例: {len(good_signal)/len(df)*100:.1f}%")
    print(f"差信号比例: {len(poor_signal)/len(df)*100:.1f}%")
    
    # 分析睡眠相关模式
    print("\n=== 睡眠相关模式分析 ===")
    
    # 计算放松指标（高Alpha波 + 低Beta波）
    df['relaxation_index'] = (df['highAlpha'] + df['lowAlpha']) / (df['lowBeta'] + df['highBeta'] + 1)
    
    # 计算困倦指标（高Theta波 + 高Delta波）
    df['drowsiness_index'] = (df['theta'] + df['delta']) / (df['total_power'] + 1)
    
    print(f"平均放松指标: {df['relaxation_index'].mean():.3f}")
    print(f"平均困倦指标: {df['drowsiness_index'].mean():.3f}")
    
    # 识别可能的睡眠阶段
    def identify_sleep_stage(row):
        if row['poorSignal'] > 50:
            return '信号差'
        elif row['attention'] < 30 and row['meditation'] > 60:
            if row['delta'] > row['theta'] * 2:
                return '深度放松/浅睡眠'
            elif row['theta'] > row['delta']:
                return '困倦状态'
            else:
                return '冥想状态'
        elif row['attention'] > 60:
            return '清醒专注'
        else:
            return '普通清醒'
    
    df['sleep_stage'] = df.apply(identify_sleep_stage, axis=1)
    print("\n识别的状态分布:")
    print(df['sleep_stage'].value_counts())
    
    # 生成可视化图表
    create_visualizations(df, time_stats)
    
    return df, time_stats

def create_visualizations(df, time_stats):
    """创建可视化图表"""
    
    plt.figure(figsize=(15, 12))
    
    # 1. 注意力和冥想随时间变化
    plt.subplot(3, 2, 1)
    plt.plot(time_stats['time_window'], time_stats['attention'], label='注意力', color='red', alpha=0.7)
    plt.plot(time_stats['time_window'], time_stats['meditation'], label='冥想', color='blue', alpha=0.7)
    plt.title('注意力和冥想状态随时间变化')
    plt.xlabel('时间')
    plt.ylabel('数值')
    plt.legend()
    plt.xticks(rotation=45)
    
    # 2. 脑电波频段分布
    plt.subplot(3, 2, 2)
    wave_columns = ['delta', 'theta', 'lowAlpha', 'highAlpha', 'lowBeta', 'highBeta', 'lowGamma', 'midGamma']
    wave_means = [df[col].mean() for col in wave_columns]
    plt.bar(wave_columns, wave_means, color='skyblue', alpha=0.7)
    plt.title('各脑电波频段平均强度')
    plt.xlabel('频段')
    plt.ylabel('平均强度')
    plt.xticks(rotation=45)
    
    # 3. 状态分布饼图
    plt.subplot(3, 2, 3)
    sleep_stage_counts = df['sleep_stage'].value_counts()
    plt.pie(sleep_stage_counts.values, labels=sleep_stage_counts.index, autopct='%1.1f%%')
    plt.title('识别状态分布')
    
    # 4. 信号质量随时间变化
    plt.subplot(3, 2, 4)
    plt.plot(time_stats['time_window'], time_stats['poorSignal'], color='orange', alpha=0.7)
    plt.title('信号质量随时间变化')
    plt.xlabel('时间')
    plt.ylabel('信号质量指标')
    plt.xticks(rotation=45)
    
    # 5. 注意力vs冥想散点图
    plt.subplot(3, 2, 5)
    plt.scatter(df['attention'], df['meditation'], alpha=0.5, c=df['poorSignal'], cmap='viridis')
    plt.xlabel('注意力')
    plt.ylabel('冥想')
    plt.title('注意力vs冥想关系')
    plt.colorbar(label='信号质量')
    
    # 6. 主要脑电波随时间变化
    plt.subplot(3, 2, 6)
    plt.plot(time_stats['time_window'], time_stats['delta'], label='Delta', alpha=0.7)
    plt.plot(time_stats['time_window'], time_stats['theta'], label='Theta', alpha=0.7)
    plt.plot(time_stats['time_window'], time_stats['lowAlpha'], label='Alpha', alpha=0.7)
    plt.plot(time_stats['time_window'], time_stats['lowBeta'], label='Beta', alpha=0.7)
    plt.title('主要脑电波随时间变化')
    plt.xlabel('时间')
    plt.ylabel('强度')
    plt.legend()
    plt.xticks(rotation=45)
    
    plt.tight_layout()
    plt.savefig('d:\\python\\new_brain_wave\\clean_data\\eeg_pattern_analysis.png', dpi=300, bbox_inches='tight')
    plt.show()
    
    print("\n图表已保存为 'eeg_pattern_analysis.png'")

if __name__ == "__main__":
    file_path = "d:\\python\\new_brain_wave\\clean_data\\eeg_data_exc.csv"
    
    try:
        df, time_stats = analyze_eeg_patterns(file_path)
        
        print("\n=== 分析总结 ===")
        print("1. 数据质量: 检查了信号质量和数据完整性")
        print("2. 状态识别: 基于注意力、冥想和脑电波特征识别了不同状态")
        print("3. 时间趋势: 分析了各指标随时间的变化模式")
        print("4. 睡眠模式: 识别了可能的睡眠相关状态")
        print("5. 可视化: 生成了多维度的分析图表")
        
    except Exception as e:
        print(f"分析过程中出现错误: {e}")